<template>
  <a-layout>
    <a-layout-content style="padding: 24px;" >
      <div>
        <a-row class="headRow">
          <a-col :span="12">
            <h3>链上数据</h3>
          </a-col>
          <a-col>
            <div style="display: flex">
              <a-input v-model:value="searchData" ></a-input>
              <a-button @click="handleSearch">搜索实验数据集名</a-button>
            </div>
          </a-col>
        </a-row>
      </div>
      <!-- 表格内容 -->
      <a-table :columns="columns" :data-source="tableData" :pagination="false" :scroll="{y:'65vh'}">
        <template #bodyCell="{column, record}">
          <template v-if="column.key === 'action' ">
            <span>
              <a-button 
                :disabled="record.isRequesting || record.isPending || record.isGranted"
                :type="getButtonType(record)"
                @click="handleRequest(record)"
              >
                {{ getButtonText(record) }}
              </a-button>
            </span>
          </template>
        </template>
      </a-table>
    </a-layout-content>
  </a-layout>
</template>

<script>
import { defineComponent } from 'vue';
import {Layout, Table, Button, Space, message} from 'ant-design-vue';
import axiosInstance from '@/axios/axios.js';

export default defineComponent({
  components: {
  },
  data() {
    return {
      searchData: "",
      tableData: [],
      pendingRequests: new Set(), // 直接初始化空集合
      grantedAccess: new Set(), // 直接初始化空集合
      columns: [
        {
          title: '数据拥有者',
          dataIndex: 'grantorName',
          key: 'grantorName'
        },
        {
          title: '实验数据集名',
          dataIndex: 'name',
          key: 'name'
        },
        {
          title: '描述',
          dataIndex: 'description',
          key: 'description'
        },
        {
          title: '实验者',
          dataIndex: 'creator',
          key: 'creator'
        },
        {
          title: '领域',
          dataIndex: 'field',
          key: 'field'
        },
        {
          title: '操作',
          key: 'action',
          scopedSlots: { customRender: 'action' }
        }
      ],
    };
  },
  async created() {
    // 检查登录状态
    if (!this.$cookies.get('jwt') || !sessionStorage.getItem("isLogin")) {
      message.warning('请先登录');
      this.$router.push('/login');
      return;
    }

    // 检查必要的cookie
    const requiredCookies = ['jwt', 'username'];
    const missingCookies = requiredCookies.filter(cookie => !this.$cookies.get(cookie));
    if (missingCookies.length > 0) {
      message.error('登录信息不完整，请重新登录');
      this.$router.push('/login');
      return;
    }
    
    // 先加载授权状态，再加载数据
    await this.loadAccessStatus();
    await this.loadData();
  },
  methods: {
    getButtonType(record) {
      if (record.isGranted) return 'success';
      if (record.isPending || this.pendingRequests.has(record.experiment_set_id)) return 'default';
      if (record.isRequesting) return 'default';
      return 'primary';
    },
    getButtonText(record) {
      if (record.isRequesting) return '请求中...';
      if (record.isGranted) return '已授权';
      if (record.isPending || this.pendingRequests.has(record.experiment_set_id)) return '等待授权';
      return '申请授权';
    },
    async loadAccessStatus() {
      try {
        // 获取授权请求状态
        const requestResponse = await axiosInstance({
          method: "POST",
          url: "/grant/getGrantRequestsBySenderAddress",
          data: {
            userAddress: this.$cookies.get("userAddress")  // 从cookie中获取区块链地址
          },
          headers: {
            Authorization: `Bearer ${this.$cookies.get("jwt")}`  // 添加JWT token
          }
        });

        console.log('Grant requests response:', requestResponse);

        // 清空并更新状态集合
        this.pendingRequests.clear();
        this.grantedAccess.clear();

        // 根据后端返回更新状态
        const grantRequests = requestResponse.data?.data?.grantRequests;
        console.log('Grant requests:', grantRequests);

        if (grantRequests && grantRequests.length > 0) {
          grantRequests.forEach(request => {
            if (request.status === 1) { // status=1表示等待授权
              this.pendingRequests.add(request.experiment_set_id);
            } else if (request.status === 2) { // status=2表示已授权
              this.grantedAccess.add(request.experiment_set_id);
            }
          });
        }
        
        console.log('Updated authorization status:', {
          pendingRequests: Array.from(this.pendingRequests),
          grantedAccess: Array.from(this.grantedAccess)
        });

        // 更新表格数据状态
        this.tableData = this.tableData.map(item => ({
          ...item,
          isPending: this.pendingRequests.has(item.experiment_set_id),
          isGranted: this.grantedAccess.has(item.experiment_set_id)
        }));
      } catch (error) {
        console.error('获取授权状态失败:', error);
        if (error.response?.status === 401) {
          message.error('登录已过期，请重新登录');
          this.$router.push('/login');
        } else {
          message.error(error.message || '获取授权状态失败');
        }
      }
    },
    async loadData() {
      try {
        const username = this.$cookies.get("username");
        
        if (!username) {
          message.error('用户信息不完整，请重新登录');
          this.$router.push('/login');
          return;
        }

        console.log('Requesting chain data with username:', username);
        
        const response = await axiosInstance({
          method: "GET",
          url: "/data/chain",
          params: {
            username
          }
        });

        if (response.data?.data) {
          // 合并已授权和未授权的实验集
          const grantedSets = (response.data.data.grantedSets || []).map(item => ({
            ...item,
            grantorName: item.creator,
            grantorAddress: item.owner_address,
            isRequesting: false,
            isPending: false,
            isGranted: true
          }));
const ungrantedSets = (response.data.data.ungrantedSets || []).map(item => ({
  ...item,
  grantorName: item.user_name,
  grantorAddress: item.user_address,
  isRequesting: false,
  isPending: this.pendingRequests.has(item.experiment_set_id),
  isGranted: false
}));

this.tableData = [...grantedSets, ...ungrantedSets];

// 确保状态正确
this.tableData = this.tableData.map(item => ({
  ...item,
  isPending: this.pendingRequests.has(item.experiment_set_id),
  isGranted: this.grantedAccess.has(item.experiment_set_id)
}));

          console.log('Current authorization status:', {
            pendingRequests: Array.from(this.pendingRequests),
            grantedAccess: Array.from(this.grantedAccess)
          });
          console.log('Updated table data:', this.tableData);
        }
      } catch (error) {
        console.error('获取链上数据失败:', error);
        if (error.response?.status === 401) {
          message.error('登录已过期，请重新登录');
          this.$router.push('/login');
        } else {
          message.error(`获取数据失败: ${error.response?.data?.message || error.message}`);
        }
      }
    },
    async handleRequest(record) {
      if (record.isRequesting || this.pendingRequests.has(record.experiment_set_id) || record.isGranted) return;
      
      // 设置请求状态
      const index = this.tableData.findIndex(item => item.experiment_set_id === record.experiment_set_id);
      if (index !== -1) {
        this.tableData[index].isRequesting = true;
      }
      
      try {
        const requestData = {
          senderName: this.$cookies.get("username"),
          receiverName: record.grantorName,
          receiverAddress: record.grantorAddress,
          experimentSetId: record.experiment_set_id,
          experimentSetName: record.name,
        };
        
        console.log('Sending grant request:', requestData);
        
        await axiosInstance({
          method: "POST",
          url: "/grant/createGrantRequest",
          data: requestData,
        });
        
        // 发送成功后，重新加载授权状态
        await this.loadAccessStatus();
        message.success('授权申请已发送');
      } catch (error) {
        // 恢复状态
        if (index !== -1) {
          this.tableData[index].isRequesting = false;
        }
        console.error('申请授权失败:', error);
        if (error.response?.status === 401) {
          message.error('登录已过期，请重新登录');
          this.$router.push('/login');
        } else {
          message.error(`申请失败: ${error.response?.data?.message || error.message}`);
        }
      }
    },
    async handleSearch() {
      try {
        const response = await axiosInstance({
          method: "POST",
          url: "/data/searchExperimentSet",
          data: {
            experimentSetName: this.searchData,
            username: this.$cookies.get("username")
          },
        });
        
        this.tableData = response.data.data.map(item => ({
          ...item,
          grantorName: item.user_name,
          grantorAddress: item.user_address,
          isRequesting: false,
          isPending: this.pendingRequests.has(item.experiment_set_id),
          isGranted: this.grantedAccess.has(item.experiment_set_id)
        }));
      } catch (error) {
        console.error('搜索失败:', error);
        if (error.response?.status === 401) {
          message.error('登录已过期，请重新登录');
          this.$router.push('/login');
        } else {
          message.error(`搜索失败: ${error.response?.data?.message || error.message}`);
        }
      }
    }
  }
});
</script>

<style scoped>
.headRow {
  margin: 20px;
}
.disabled {
  pointer-events: none;
  opacity: 0.5;
}
</style>
